package com.test.learnkotlin.utils

import java.io.PrintWriter
import java.io.StringWriter

/*
Kotlin 构造函数、继承
https://www.jianshu.com/p/fc54d2241ba7

Kotlin下的5种单例模式
https://www.jianshu.com/p/5797b3d0ebd0
 */
class GlobalCrashHandlerKT : Thread.UncaughtExceptionHandler {

    //饿汉式
    /*
         object GlobalCrashHandlerKT
        直接将 GlobalCrashHandlerKT 定义为 object
     */

    companion object {
        //         val INSTANCE = GlobalCrashHandlerKT()
        private var INSTANCE: GlobalCrashHandlerKT? = null
            //懒汉式
            get() {
                if (field == null) {
                    field = GlobalCrashHandlerKT()
                }
                return field
            }


        //懒汉式
        fun get(): GlobalCrashHandlerKT {
            return INSTANCE!!
        }

        //线程安全的懒汉式
        @Synchronized
        fun get2(): GlobalCrashHandlerKT {
            return INSTANCE!!
        }


        //双重校验锁式（Double Check)
        val INSTANCE2: GlobalCrashHandlerKT by lazy(mode = LazyThreadSafetyMode.SYNCHRONIZED) {
            GlobalCrashHandlerKT()
        }


        //静态内部类式
        val INSTANCE3 = GlobalCrashHandlerKTHolder.holder


    }

    private object GlobalCrashHandlerKTHolder{
        val holder = GlobalCrashHandlerKT()
    }



    init {
        Thread.setDefaultUncaughtExceptionHandler(this)
    }


    override fun uncaughtException(t: Thread, e: Throwable) {
        val crashInfo = caughtException(t, e)
        LogUitls.i("GlobalCrashHandlerKT 全局捕获到的异常信息：$crashInfo")
    }

    fun caughtException(t: Thread, throwable: Throwable): String {
        val mStringWriter = StringWriter()
        val mPrintWriter = PrintWriter(mStringWriter)
        throwable.printStackTrace(mPrintWriter)
        mPrintWriter.close()
        return mStringWriter.toString()


    }
}